package com.chenfan.ccp.plug.business.service;

import com.chenfan.ccp.plug.business.util.TaskAsyncExecutorUtil;
import com.chenfan.ccp.util.start.ApplicationContextUtil;
import com.chenfan.ccp.plug.business.entity.ActionLog;
import com.chenfan.ccp.plug.business.entity.BusinessLog;
import com.chenfan.ccp.utils.TraceIdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

//@Service
public class BusinessLogServiceImpl implements BusinessLogService {

    private final Logger logger = LoggerFactory.getLogger(BusinessLog.class);

    @Value("${spring.application.name:''}")
    private String serviceName;


    public void send(BusinessLog businessLog) {
        logger.info("发送业务日志={}", businessLog);
        businessLog.setServiceName(serviceName);
        businessLog.setIp(ApplicationContextUtil.getLocalIp());
        businessLog.setTraceId(TraceIdUtil.getTraceId());
        try {
            HttpServletRequest request = ApplicationContextUtil.getContext().getBean(HttpServletRequest.class);
            businessLog.setRequestUrl(request.getRequestURI());
            TaskAsyncExecutorUtil.send(businessLog);
        } catch (Exception e) {

        } finally {
            //clean 一个请求中 只保留开始到发送日志的记录
            BusinessCollectService.remove(TraceIdUtil.getTraceId());
        }
    }

    @Override
    public void send(ActionLog actionLog) {
        BusinessLog businessLog = BusinessCollectService.getBusinessLog(TraceIdUtil.getTraceId());
        List<ActionLog.ActionData> actionList = actionLog.getActionList();
        BeanUtils.copyProperties(actionList, businessLog);
        businessLog.setActionList(actionList);
        send(businessLog);
    }
}
